<template>
  <div id="app">
    <Navbar />
    <div class="register-wrapper">
      <div class="register-container">
        <h2>用户注册</h2>
        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label for="userName">用户名称：</label>
            <input type="text" id="userName" v-model="formData.userName" placeholder="请输入用户名称" required>
          </div>
          <div class="form-group">
            <label for="password">密码：</label>
            <input type="password" id="password" v-model="formData.password" placeholder="请输入密码" required>
          </div>
          <div class="form-group">
            <label for="confirmPassword">确认密码：</label>
            <input type="password" id="confirmPassword" v-model="formData.confirmPassword" placeholder="请再次确认密码" required>
          </div>
          <div class="form-group">
            <label for="email">电子邮箱：</label>
            <input type="email" id="email" v-model="formData.email" placeholder="请输入电子邮箱" required>
          </div>
          <div class="form-group">
            <label for="phoneNumber">手机号码：</label>
            <input type="tel" id="phoneNumber" v-model="formData.phoneNumber" placeholder="请输入手机号码" required>
          </div>
          <div class="form-group captcha-row">
            <label for="captcha">图形验证码：</label>
            <input type="text" id="captcha" v-model="formData.captcha" placeholder="请输入图形验证码" required>
            <img :src="captchaImg" alt="图形验证码" @click="refreshCaptcha">
          </div>
          <div class="form-group">
            <label for="smsCaptcha">手机验证码：</label>
            <input type="text" id="smsCaptcha" v-model="formData.smsCaptcha" placeholder="请输入手机验证码" required>
            <button type="button" :disabled="!canGetSmsCaptcha || isSmsCaptchaDisabled" @click="fetchSmsCaptcha" :class="{ 'disabled-btn':!canGetSmsCaptcha || isSmsCaptchaDisabled }">
              {{ smsCaptchaButtonText }}
            </button>
          </div>
          <div class="form-group agree-group">
            <input type="checkbox" id="agree" v-model="isAgreed" required>
            <label for="agree">同意注册协议和服务内容《<a href="#">注册协议</a>》《<a href="#">服务协议</a>》</label>
          </div>
          <div class="button-container">
            <button type="submit">注册</button>
            <button type="button" @click="goBack">返回</button>
          </div>
        </form>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import {useRouter} from 'vue-router';
import {getCaptchaImg, getSmsCaptcha, register} from "@/api/register";
import Navbar from "@/components/Navbar/Navbar.vue";
import Footer from "@/components/Footer/Footer.vue";

// 以对象形式定义响应式数据
const formData = ref({
  userName: '',
  password: '',
  confirmPassword: '',
  email: '',
  phoneNumber: '',
  uuid: '',
  captcha: '',
  smsCaptcha: ''
});

const captchaImg = ref('');
const isSmsCaptchaDisabled = ref(false);
const smsCaptchaButtonText = ref('获取手机验证码');
const countdown = ref(0);
const isAgreed = ref(false);
// 新增一个响应式变量来控制按钮是否可点击
const canGetSmsCaptcha = ref(false);

const router = useRouter();

// 刷新图形验证码的方法
const refreshCaptcha = async () => {
  try {
    const res = await getCaptchaImg({
      grantType: 'uuid'
    });
    const captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled;
    if (captchaEnabled) {
      captchaImg.value = "data:image/gif;base64," + res.data.img;
      formData.value.uuid = res.data.uuid;
    }
  } catch (error) {
    console.error('获取验证码出错:', error);
  }
};

// 获取手机验证码的方法
const fetchSmsCaptcha = async () => {
  if (!formData.value.phoneNumber || !formData.value.captcha) {
    alert('请先输入手机号码和图形验证码');
    return;
  }
  isSmsCaptchaDisabled.value = true;
  countdown.value = 60;
  const intervalId = setInterval(() => {
    if (countdown.value > 0) {
      smsCaptchaButtonText.value = `${countdown.value} 秒后重新获取`;
      countdown.value--;
    } else {
      clearInterval(intervalId);
      isSmsCaptchaDisabled.value = false;
      smsCaptchaButtonText.value = '获取手机验证码';
    }
  }, 1000);

  try {
    const response = await getSmsCaptcha({
      grantType: 'sms',
      phoneNumber: formData.value.phoneNumber,
      captcha: formData.value.captcha
    });
    alert(response.data.message);
  } catch (error) {
    console.error('获取短信验证码请求出错:', error);
    // 更详细的错误处理
    if (error.response) {
      const status = error.response.status;
      if (status === 400) {
        alert('请求参数错误，请检查输入');
      } else if (status === 500) {
        alert('服务器内部错误，请稍后重试');
      } else {
        alert('获取短信验证码失败，请稍后重试');
      }
    } else {
      alert('网络连接错误，请检查网络');
    }
  }
};

// 处理注册表单提交的方法
const handleSubmit = async () => {
  if (!formData.value.userName) {
    alert('请输入用户名称');
    return;
  }
  if (!formData.value.password) {
    alert('请输入密码');
    return;
  }
  if (!formData.value.confirmPassword) {
    alert('请确认密码');
    return;
  }
  if (formData.value.password !== formData.value.confirmPassword) {
    alert('两次输入的密码不一致');
    return;
  }
  if (!formData.value.email) {
    alert('请输入电子邮箱');
    return;
  }
  if (!formData.value.phoneNumber) {
    alert('请输入手机号码');
    return;
  }
  if (!formData.value.captcha) {
    alert('请输入图形验证码');
    return;
  }
  if (!formData.value.smsCaptcha) {
    alert('请输入手机验证码');
    return;
  }
  if (!isAgreed.value) {
    alert('请同意注册协议和服务内容');
    return;
  }
  try {
    const response = await register(formData.value);
    alert(response.data.message);
    if (response.data.success) {
      // 注册成功后的处理，如跳转到登录页
      router.push('/login');
    }
  } catch (error) {
    console.error('注册请求出错:', error);
    // 更详细的错误处理
    if (error.response) {
      const status = error.response.status;
      if (status === 400) {
        alert('请求参数错误，请检查输入');
      } else if (status === 500) {
        alert('服务器内部错误，请稍后重试');
      } else {
        alert('注册失败，请稍后重试');
      }
    } else {
      alert('网络连接错误，请检查网络');
    }
  }
};

// 返回上一页的方法
const goBack = () => {
  // 这里可以添加返回逻辑，比如返回上一页
  window.history.back();
};

// 监听手机号码和图形验证码的输入，更新按钮的可点击状态
watch([() => formData.value.phoneNumber, () => formData.value.captcha], () => {
  canGetSmsCaptcha.value = formData.value.phoneNumber && formData.value.captcha;
});

// 组件挂载时刷新图形验证码
onMounted(() => {
  refreshCaptcha();
});
</script>

<style scoped>
/* 整体页面布局 */
body {
  margin: 0;
  padding: 0;
  font-family: Arial, sans-serif;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 调整中间部分的背景颜色 */
.register-container {
  width: 100%;
  max-width: 800px;
  padding: 40px;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9; /* 设置默认背景颜色 */
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  margin: 100px auto;
  flex: 1; /* 使中间部分占据剩余空间 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

h2 {
  text-align: left; /* 将标题左对齐 */
  margin-bottom: 60px;
  color: #333;
}

.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.form-group label {
  flex: 0 0 150px;
  margin-bottom: 0;
  margin-right: 20px;
  font-size: 14px;
  color: #555;
  text-align: right; /* 标签右对齐 */
}

.form-group input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  border-color: #007BFF;
  outline: none;
}

.captcha-row img {
  width: 120px;
  height: auto;
  margin-left: 20px;
  cursor: pointer;
}

button {
  padding: 12px 20px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #0056b3;
}

/* 调整获取手机验证码按钮和输入框间距 */
.form-group > button {
  margin-left: 20px;
}

.agree-group {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto; /* 让元素在父容器中水平居中 */
  width: fit-content; /* 根据内容自动调整宽度，使容器更紧凑 */
}

.agree-group input {
  margin-right: 5px; /* 减小 checkbox 和标签之间的间距，原来是 15px，现在设为 5px */
  width: auto;
}

.agree-group label {
  font-size: 14px;
  color: #555;
  text-align: left; /* 协议标签左对齐 */
  flex: none; /* 取消协议标签的 flex 分配 */
  line-height: 1.2; /* 调整行高使文本更紧凑 */
  padding: 0;
}

.button-container {
  text-align: center;
  margin-top: 30px;
}

.button-container button {
  width: auto;
  padding: 12px 40px;
  margin: 0 10px; /* 增加按钮之间的间距 */
}

.button-container button:nth-child(2) {
  background-color: #6c757d; /* 修改返回按钮的背景颜色 */
}

.button-container button:nth-child(2):hover {
  background-color: #5a6268; /* 修改返回按钮悬停时的背景颜色 */
}

/* 媒体查询，小屏幕适配 */
@media (max-width: 480px) {
  .register-container {
    max-width: 100%;
    padding: 20px;
  }

  .form-group {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-group label {
    margin-bottom: 10px;
    text-align: left; /* 小屏幕下标签左对齐 */
  }

  .captcha-row img {
    margin-top: 10px;
    margin-left: 0;
  }

  .form-group > button {
    margin-left: 0;
    margin-top: 10px;
  }
}

/* 新增禁用按钮样式 */
.disabled-btn {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>